package controller;

import pojo.User;
import service.IUserService;
import service.impl.UserServiceImpl;
import utils.NoLoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {
    private IUserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NoLoginUtil.doVerify(request);
        request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        boolean isAdmin = "on".equals(request.getParameter("is-admin"));
        String nickName = request.getParameter("nick-name");
        String realName = request.getParameter("real-name");
        String shipAddress = request.getParameter("ship-address");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        User user = new User(nickName, realName, password, phone, shipAddress, isAdmin);
        userService.insertUser(user);
        request.setAttribute("user", user);
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }
}
